%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%% @end
%%%-------------------------------------------------------------------
-module(rank_svr).

-behaviour(gen_server).
-include("rank.hrl").
-include_lib("stdlib/include/ms_transform.hrl").

-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
    code_change/3]).

-define(SERVER, ?MODULE).

-record(state, {
    rank_type,
    tab_name
}).

%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link(RankType) ->
    gen_server:start_link({local, ?RANK_SVR_NAME(RankType)}, ?MODULE, [RankType], []).

init([RankType]) ->
    TabName = ?ETS_RANK(RankType),
    ets:new(TabName, [named_table, {keypos, #rank_data.rank_key}, {read_concurrency, true}, ordered_set, protected]),
    {ok, #state{rank_type = RankType, tab_name = TabName}}.

handle_call(_Request, _From, State = #state{}) ->
    {reply, ok, State}.

handle_cast({submit, #rank_data{key = Key} = RankData}, State = #state{tab_name = TabName}) ->
    Ms = ets:fun2ms(fun({M, AccRankData}) when AccRankData#rank_data.key==Key -> AccRankData end),
    ets:match_delete(TabName, Ms),
    ets:insert(TabName, RankData),
    {noreply, State};

handle_cast(_Request, State = #state{}) ->
    {noreply, State}.

handle_info(_Info, State = #state{}) ->
    {noreply, State}.

terminate(_Reason, _State = #state{}) ->
    ok.

code_change(_OldVsn, State = #state{}, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================
